import Vue from 'vue'
import Vuex from 'vuex'
import store from '../index'
import { Notification } from 'element-ui'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    websock: null
  },
  mutations: {
    WEBSOCKET_INIT: function(state, url) {
      state.websock = new WebSocket(url)
      state.websock.onopen = function() {
        console.log('连接成功！')
      }
      state.websock.onmessage = function(callBack) {
        console.log('ws接收消息！')
        const msg = callBack.data
        if (msg === '提醒') {
          store.dispatch('IncreaseMsgNum')
        } else if (msg.indexOf('{') === -1) {
          this.instance = Notification.info({
            title: '答辩人员通知',
            dangerouslyUseHTMLString: true,
            message: msg,
            duration: 60000 * 30
          })
        } else {
          const data = JSON.parse(msg)
          const name = data.name
          const id = msg.substring(msg.indexOf(':') + 1, msg.indexOf(','))
          let path = ''
          if (store.getters.roles === '1') {
            path = '#/teacher/message?messageId=' + id
          } else {
            path = '#/student/message?messageId=' + id
          }
          const title = '打分提醒'
          const html = '您有一个为<strong>' + name + '</strong>的待<strong>评分</strong>消息，三十分钟内有效，点击' +
            '<a href="' + path + '" class="" style="color: rgb(64, 158, 255);"> 查看详情 </a>，或点击“消息”查看。'
          this.instance = Notification.info({
            title: title,
            dangerouslyUseHTMLString: true,
            message: html,
            duration: 60000 * 30,
            onClick: () => {
              if (event.target.nodeName === 'A') {
                this.instance.close()
              }
            }
          })
        }
      }
      state.websock.onerror = function(e) { // 错误
        console.log('ws错误!')
        console.log(e)
      }
      state.websock.onclose = function(e) { // 关闭
        console.log('ws关闭！')
        console.log(e)
      }
      // state.websock.binaryType = 'arraybuffer'
    },
    WEBSOCKET_SEND(state, p) {
      console.log('ws发送！')
      state.websock.send(p)
    }
  },
  actions: {
    WEBSOCKET_INIT({ commit }, url) {
      commit('WEBSOCKET_INIT', url)
    },
    WEBSOCKET_SEND({ commit }, p) {
      commit('WEBSOCKET_SEND', p)
    }
  }
})
